<?php
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../extend/qiniu/vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\PersistentFile;

// 添加文档函数
function add_document($account, $body) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT user_docu FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_docu'] <= 0) {
            return json_response(500, '账号文档余额不足，请充值');
        }
        $new_docu = $user['user_docu'] - 1;
        $stmt = $pdo->prepare("UPDATE star_user SET user_docu = :user_docu WHERE account = :account");
        $stmt->bindParam(':user_docu', $new_docu, PDO::PARAM_INT);
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $stmt = $pdo->prepare("INSERT INTO star_docu (account, body) VALUES (:account, :body)");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':body', $body, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '文档添加成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 获取文档列表函数
function docu_list($account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        if (!$stmt->fetchColumn()) {
            return json_response(500, '账号未注册');
        }
        $stmt = $pdo->prepare("SELECT uid, body FROM star_docu WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (empty($documents)) {
            return json_response(500, '该账号下没有文档');
        }
        return json_response(200, '文档列表获取成功', $documents);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 获取单个文档内容函数
function get_document($account, $uid) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        if (!$stmt->fetchColumn()) {
            return json_response(500, '账号未注册');
        }
        $stmt = $pdo->prepare("SELECT body FROM star_docu WHERE account = :account AND uid = :uid");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        $document = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$document) {
            return json_response(500, '文档不存在');
        }
        $body = nl2br($document['body']);
        header('Content-Type: text/html; charset=utf-8');
        echo $body;
        exit;
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 删除文档函数
function delete_document($account, $uid) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        if (!$stmt->fetchColumn()) {
            return json_response(500, '账号未注册');
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_docu WHERE account = :account AND uid = :uid");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        if (!$stmt->fetchColumn()) {
            return json_response(500, '文档不存在');
        }
        $stmt = $pdo->prepare("DELETE FROM star_docu WHERE account = :account AND uid = :uid");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        return json_response(200, '文档删除成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 网盘: 上传文件函数
function upload_to_qiniu($account, $file, $file_name, $file_introduce) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT cloud_disk, cloud_condition FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号不存在');
        }
        if ($user['cloud_condition'] == 1) {
            return json_response(500, '账号网盘已被封禁');
        }
        $file_size = $file['size'] / (1024 * 1024);
        if ($user['cloud_disk'] < $file_size) {
            return json_response(500, '账号容量不足，请前往充值');
        }
        $accessKey = QINIU_ACCESS_KEY;
        $secretKey = QINIU_SECRET_KEY;
        $bucket = QINIU_BUCKET_NAME;
        $domainOfBucket = QINIU_DOMAIN_OF_BUCKET;
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        $filePath = $file['tmp_name'];
        $original_file_name = basename($file['name']);
        $key = "繁控星理/$account/$original_file_name";
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return json_response(500, '上传失败: ' . $err->getMessage());
        }
        $new_cloud_disk = $user['cloud_disk'] - $file_size;
        $stmt = $pdo->prepare("UPDATE star_user SET cloud_disk = :new_cloud_disk WHERE account = :account");
        $stmt->bindParam(':new_cloud_disk', $new_cloud_disk, PDO::PARAM_STR);
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $record_time = date('Y-m-d H:i:s');
        $file_url = $domainOfBucket . '/' . $key;
        $stmt = $pdo->prepare("
            INSERT INTO star_user_cloud (account, file_url, record_time, file_name, file_introduce)
            VALUES (:account, :file_url, :record_time, :file_name, :file_introduce)
        ");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':file_url', $file_url, PDO::PARAM_STR);
        $stmt->bindParam(':record_time', $record_time, PDO::PARAM_STR);
        $stmt->bindParam(':file_name', $file_name, PDO::PARAM_STR);
        $stmt->bindParam(':file_introduce', $file_introduce, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '文件上传成功', [
            'file_url' => $file_url,
            'file_size' => $file_size,
            'remaining_cloud_disk' => $new_cloud_disk,
            'record_time' => $record_time,
            'file_name' => $file_name,
            'file_introduce' => $file_introduce
        ]);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 网盘: 删除文件函数
function file_delete($account, $uid) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT cloud_condition FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号不存在');
        }
        if ($user['cloud_condition'] == 1) {
            return json_response(500, '账号网盘已被封禁');
        }
        $stmt = $pdo->prepare("SELECT file_url FROM star_user_cloud WHERE account = :account AND uid = :uid");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        $file_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$file_info) {
            return json_response(500, '文件不存在');
        }
        $accessKey = QINIU_ACCESS_KEY;
        $secretKey = QINIU_SECRET_KEY;
        $bucket = QINIU_BUCKET_NAME;
        $auth = new Auth($accessKey, $secretKey);
        $url = parse_url($file_info['file_url']);
        $file_key = ltrim($url['path'], '/');
        $ret = $auth->deleteFile($bucket, $file_key);
        if ($ret !== null) {
            return json_response(500, '文件删除失败: ' . $ret->getMessage());
        }
        $stmt = $pdo->prepare("DELETE FROM star_user_cloud WHERE account = :account AND uid = :uid");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $uid, PDO::PARAM_INT);
        $stmt->execute();
        return json_response(200, '文件删除成功');
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}

// 网盘: 获取文件列表函数
function file_list($account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT cloud_condition FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            return json_response(500, '账号不存在');
        }
        if ($user['cloud_condition'] == 1) {
            return json_response(500, '账号网盘已被封禁');
        }
        $stmt = $pdo->prepare("
            SELECT uid, file_url, record_time, file_name, file_introduce 
            FROM star_user_cloud 
            WHERE account = :account
        ");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $files = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if (empty($files)) {
            return json_response(500, '该账号下没有文件');
        }
        return json_response(200, '文件列表获取成功', $files);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}